package com.jxlc.common.core.redis;

import com.jxlc.common.constant.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;

import static com.jxlc.common.constant.RedisConst.ACCESS_TOKEN;
import static com.jxlc.common.constant.RedisConst.VERIFY_KEY;

/**
 * token redis 工具类
 *
 **/
@Component
public class TokenRedisCache
{

    @Resource
    private RedisCache redisCache;

    /**
     * 验证码缓存。
     */
    public <T> void setVerifyKey(final String key, final T value)
    {
        redisCache.setMinuteCache(VERIFY_KEY + key, value, Constants.CAPTCHA_EXPIRATION);
    }

    /**
     * 获得验证码缓存。
     */
    public <T> T getVerifyKey(final String key) {
        return redisCache.getCacheObject(VERIFY_KEY + key);
    }

    /**
     * 删除验证码缓存
     */
    public void delVerifyKey(final String key)
    {
        redisCache.deleteObject(VERIFY_KEY + key);
    }

    public <T> void setToken(final String key, final T value, final Integer timeout)
    {
        redisCache.setMinuteCache(ACCESS_TOKEN + key, value, timeout);
    }

    /**
     * 获得访问令牌缓存。
     */
    public <T> T getToken(final String key)
    {
        return redisCache.getCacheObject(ACCESS_TOKEN + key);
    }

    /**
     * 删除访问令牌缓存
     */
    public void delToken(final String key)
    {
        redisCache.deleteObject(ACCESS_TOKEN + key);
    }

    /**
     * 批量删除访问令牌缓存
     */
    public void delToken(final Collection<String> collection, final String key)
    {
        Collection<String> temp = new ArrayList<>();
        for (String s : collection) {
            temp.add(ACCESS_TOKEN + key + ":" + s);
        }
        redisCache.deleteObject(temp);
    }

    public boolean hasToken(String key) {
        return redisCache.hasKey(ACCESS_TOKEN + key);
    }

}
